<template>
  <c-back-wrap go-page="经销商冻结/解冻管理" :before-call-back="$goBackCall" current-page="账号冻结申请">
    <c-title title="基本信息">
      <CustomerBaseInfo
        ref="customerBaseInfo"
        v-model="customerFormData"
        :before-params="paramsJson=>{
          paramsJson.filtersRaw.push({id:'oneCategoryCode',property:'oneCategoryCode',value:'Z230',operator:'<>'})
          $codeOrName(paramsJson.filtersRaw, 'code', 'name')
          return paramsJson
        }"
        :start-observe="startObserve"
        :detail="detail"
        @change="handleCustomerChange"
      />
    </c-title>
    <c-title title="冻结管理">
      <QupFormContainer :column="3">
        <el-form ref="form" :model="freezeFormData" :rules="freezeFromRules" label-width="120px">
          <el-form-item prop="reportType" label="提报类型">
            <c-dict-range-view :value="freezeFormData.reportType" dict-type-code="CTM_REPORT_TYPE" />
          </el-form-item>
          <el-form-item prop="type" label="冻结类型">
            <c-dict-select v-model="freezeFormData.type" dict-type-code="CTM_FREEZE_UNFREEZE_TYPE" placeholder="冻结类型" @change="handleTypeChange" />
          </el-form-item>
          <el-form-item v-if="['D', 'E'].includes(freezeFormData.type)" prop="type" label="冻结细分类型">
            <c-dict-select v-model="freezeFormData.subType" dict-type-code="CTM_UNFREEZE_SUB_TYPE" :include="subTypeInclude" placeholder="冻结细分类型" />
          </el-form-item>
          <el-form-item prop="executeTime" label="首次执行时间">
            <el-date-picker v-model="freezeFormData.executeTime" type="date" value-format="yyyy-MM-dd" format="yyyy-MM-dd" placeholder="请选择执行时间" clearable />
          </el-form-item>
          <el-form-item prop="cause" label="冻结原因" :span="24">
            <el-input v-model="freezeFormData.cause" type="textarea" show-word-limit maxlength="1024" :autosize="{minRows: 2}" placeholder="冻结原因" />
          </el-form-item>
          <el-form-item prop="remark" label="备注" :span="24">
            <el-input v-model="freezeFormData.remark" type="textarea" show-word-limit maxlength="1024" :autosize="{minRows: 2}" placeholder="备注" />
          </el-form-item>
          <el-form-item label="冻结范围" prop="tableData" :span="24">
            <FreezeTable :table-data="freezeFormData.tableData" type="edit" />
          </el-form-item>
        </el-form>
      </QupFormContainer>
    </c-title>
    <div class="btn-center">
      <c-button type="default" @click="handleCancel">取消</c-button>
      <c-button type="primary" @click="handleSubmit">确定</c-button>
    </div>
  </c-back-wrap>
</template>
<script>
import { freezeAndThawSubmit, freezeAndThawDetail } from '@/api/channelTask2/freezeAndThaw'
import FreezeTable from './freezeTable'
import CustomerBaseInfo from './CustomerBaseInfo'
import { queryByCustomerCode } from '@/api/channelTask2/change'

export default {
  name: 'FreezeArchive',
  components: {
    FreezeTable,
    CustomerBaseInfo
  },
  props: {
    id: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      customerFormData: {},
      freezeFormData: {
        cause: '', //	冻结原因
        changeCode: '', //	变更单号
        id: '', //	ID
        isInvolveDeposit: '', //	是否涉及整改保证金
        isInvolveReportPic: '', //	是否涉及报图
        lastReportPicArea: '', //	最近报图面积
        lastReportPicTime: '', //	最近报图时间
        remark: '', //	备注
        reportType: 'B', //	提报类型
        type: '', //	冻结解冻类型
        subType: '',
        executeTime: '', // 首次执行时间
        tableData: [] // 冻结范围
      },
      startObserve: false,
      detail: {}
    }
  },
  computed: {
    subTypeInclude() {
      // 选择违价类时，需控制必填，选择范围：促销违价/正价软体违价；
      // 选择招聘类时，需控制必填，选择范围：家具顾问招聘不力/设计师招聘不力/安装技师招聘不力；
      if (this.freezeFormData.type === 'D') {
        return ['A', 'B']
      }
      if (this.freezeFormData.type === 'E') {
        return ['C', 'D', 'E']
      }
      return []
    },
    freezeFromRules() {
      return {
        reportType: [{ required: true, message: '请选择提报类型', trigger: 'change' }],
        type: [{ required: false, message: '请选择冻结类型', trigger: 'change' }],
        subType: [{ required: ['D', 'E'].includes(this.freezeFormData.type), message: '请选择冻结细分类型', trigger: 'change' }],
        executeTime: [{ required: false, message: '请选择执行时间', trigger: 'change' }],
        tableData: [{ required: true, validator: (r, v, c) => {
          if (!v || v.every(e => [0, '0'].includes(e.isChange))) {
            c(new Error('请选择冻结范围'))
          } else {
            c()
          }
        }, trigger: 'change' }],
        cause: [{ required: false, message: '请输入冻结原因', trigger: 'change' }]
      }
    }
  },
  created() {
    if (this.id) {
      this.getDetailData().then(() => {
        setTimeout(() => {
          this.startObserve = true
        }, 200)
      })
    } else {
      this.startObserve = true
    }
  },
  methods: {
    handleTypeChange() {
      this.$set(this.freezeFormData, 'subType', '')
    },
    getDetailData() {
      this.loading = true
      return freezeAndThawDetail(this.id).then(res => {
        this.detail = res.data
        this.initFormData()
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    initFormData() {
      const detail = JSON.parse(JSON.stringify(this.detail))
      this.customerFormData = detail
      this.freezeFormData = detail.freezeDTO
      this.$set(this.freezeFormData, 'tableData', detail.rangeDTOS || [])
    },
    handleCancel() {
      this.$goBackCall().then(this.$pageStack.pop)
    },
    handleCustomerChange(customerCode) {
      this.$set(this.freezeFormData, 'tableData', [])
      if (!customerCode) return
      queryByCustomerCode(customerCode).then(res => {
        this.$set(this.freezeFormData, 'tableData', res.data || [])
      })
    },
    async validate() {
      await this.$refs.customerBaseInfo.validate()
      await this.$refs.form.validate()
      return Promise.resolve(true)
    },
    getPostData() {
      const data = {}

      Object.assign(data, this.$deepClone(this.customerFormData))

      data.freezeDTO = this.$deepClone(this.freezeFormData)

      data.rangeDTOS = this.$deepClone(data.freezeDTO.tableData)
      delete data.freezeDTO.tableData

      data.type = 'E'
      return data
    },
    handleSubmit() {
      return this.validate().then(() => {
        return freezeAndThawSubmit(this.getPostData()).then(res => {
          this.$message.success('操作成功!')
          this.$pageStack.pop('onPage')
        })
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.change-table-title{
  display: flex;
  justify-content: flex-start;
  align-items: center;
  &>span{
    color: #333;
    font-size: 16px;
    font-weight: 600;
    margin-right: 10px;
  }
}
</style>
